package softwaretest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import softwaretest.Domain.CameraToken;
import softwaretest.repository.CameraTokenRepository;

import java.util.Map;

@Service
public class TokenCameraService {

    @Autowired
    private CameraTokenRepository cameraTokenRepository;

    private static final String TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken"; // 替换为实际token请求URL
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e"; // 实验提供的账号

    public String getToken() {
        CameraToken token = cameraTokenRepository.findTopByOrderByIdDesc();

        // 检查 token 是否存在且未过期
        if (token != null && !token.isExpired()) {
            return token.getAccessToken(); // 返回 accessToken 字符串
        }

        // 如果没有有效的 token，重新请求 token
        return requestNewToken(); // 直接返回新的 accessToken
    }

    private String requestNewToken() {
        RestTemplate restTemplate = new RestTemplate();

        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "application/json");

        // 直接在代码中写入请求体
        String requestBody = "{ \"accountId\": \"" + ACCOUNT_ID + "\" }";

        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求并处理响应
        ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(
                TOKEN_URL, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Map<String, Object>>() {});

        // 获取响应体
        Map<String, Object> responseBody = responseEntity.getBody();
        if (responseBody != null && "200".equals(responseBody.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
            String accessToken = (String) data.get("accessToken");
            Long expireTime = (Long) data.get("expireTime");

            if (accessToken != null && expireTime != null) {
                CameraToken newToken = new CameraToken();
                newToken.setAccessToken(accessToken);
                newToken.setExpireTime(expireTime);
                // 保存新 token 到数据库
                cameraTokenRepository.save(newToken);
                return accessToken; // 返回新的 accessToken
            }
        }

        throw new RuntimeException("Failed to retrieve a new token"); // 处理获取 token 失败的情况
    }
}